define(function (require, exports, module) {
    require('./css/style.css')
    const streetStyle = require('../../../map/mapbox/style/street.js').onload();
    const imageStyle = require('../../../map/mapbox/style/image.js').onload();
    const drawStyle = require('../../../map/mapbox/style/draw.js').onload();

    const {DirectSelect} = require('../../../map/mapbox/modes/DirectSelect.js').onload();
    const {SimpleSelect} = require('../../../map/mapbox/modes/SimpleSelect.js').onload();
    const {DrawCenter, DrawCenterEvents} = require('../../../map/mapbox/modes/DrawCenter.js').onload();
    const Compare = require('../../../map/mapbox/compare/compare.js').onload();
    const Constants = require('../../../map/mapbox/modes/utils/constants.js').onload();
    const ElMessage = window.ELEMENT.Message

    function onload() {
        // 自身图层和数据源共用ID
        const selfId = "point-self"
        // 兄弟图层和数据源共用ID
        const brothersId = "point-brothers"
        // 父网格图层和数据源共用ID
        const parentId = "point-parent"

        return {
            template: require('./Widget.html'),
            name: 'DrawPoint',
            props: {
                title: {
                    type: String,
                    required: false,
                    default: ""
                },
                // 类型：基础地址：address、实有设施：equipment
                dataType: {
                    type: String,
                    required: true
                },
                // 数据ID
                dataId: {
                    type: Number,
                    required: true
                },
                // 数据权限
                dataPermission: {
                    type: Array,
                    required: false,
                    default: () => []
                }
            },
            mounted() {
            },
            created() {
                const mapConfig = window.config.map
                this.mapCenter = mapConfig.center
                this.minZoom = mapConfig.minZoom
                this.maxZoom = mapConfig.maxZoom
            },
            data() {
                return {
                    minZoom: 9,
                    maxZoom: 9,
                    // A图
                    mapA: undefined,
                    // B图
                    mapB: undefined,
                    // A绘制控件
                    drawA: undefined,
                    // B绘制控件
                    drawB: undefined,
                    open: false,
                    // 地图默认中心点
                    mapCenter: [124.54560959511093, 47.69965016453599],
                    // 尚未绘制父网格
                    noParent: false,
                    parent: [],
                    // 是否初始加载
                    firstLoad: true,
                    // 是否已有点位
                    hasData: false
                }
            },
            methods: {
                toDraw() {
                    this.open = true
                    this.$nextTick(() => {
                        this.initMap()
                    })
                },
                // 初始化地图
                initMap() {
                    this.noParent = false
                    const before = this.addMap('before', streetStyle)
                    // const before = this.addMap('before', 'mapbox://styles/mapbox/streets-v11')
                    this.mapA = before.map
                    this.drawA = before.draw
                    const after = this.addMap('after', imageStyle)
                    // const after = this.addMap('after', 'mapbox://styles/mapbox/satellite-streets-v11')
                    this.mapB = after.map
                    this.drawB = after.draw

                    this.mapA.on(DrawCenterEvents.UPDATE_POINT_CENTER, ({features}) => {
                        const feature = features[0];
                        const geometry = feature.geometry;

                        if (!turf.booleanPointInPolygon(turf.point(geometry.coordinates), this.parent, {ignoreBoundary: true})) {
                            this.drawA.delete(feature.id)
                            setTimeout(() => {
                                this.drawA.changeMode("draw_center")
                            }, 300)
                            ElMessage.error('不能在父网格之外绘制点位! ')
                            return false
                        }

                        $.ajax({
                            url: alluse.bigcenter + '/gis/' + this.dataType + '/update-center/' + this.dataId,
                            contentType: 'application/json;charset=utf-8',
                            type: 'POST',
                            data: JSON.stringify(geometry),
                            success: res => {
                                if (res.code === 200) {
                                    this.drawA.delete(feature.id)
                                    this.drawB.changeMode(Constants.modes.SIMPLE_SELECT)
                                    ElMessage.success('绘制点位成功！')

                                    this.initData(this.mapA)
                                    this.initData(this.mapB)
                                }
                            }
                        })
                    })

                    this.mapB.on(DrawCenterEvents.UPDATE_POINT_CENTER, ({features}) => {
                        const feature = features[0];
                        const geometry = feature.geometry;

                        if (!turf.booleanPointInPolygon(turf.point(geometry.coordinates), this.parent, {ignoreBoundary: true})) {
                            this.drawB.delete(feature.id)
                            setTimeout(() => {
                                this.drawB.changeMode("draw_center")
                            }, 300)
                            ElMessage.error('不能在父网格之外绘制点位! ')
                            return false
                        }

                        $.ajax({
                            url: alluse.bigcenter + '/gis/' + this.dataType + '/update-center/' + this.dataId,
                            contentType: 'application/json;charset=utf-8',
                            type: 'POST',
                            data: JSON.stringify(geometry),
                            success: res => {
                                if (res.code === 200) {
                                    this.drawB.delete(feature.id)
                                    this.drawA.changeMode(Constants.modes.SIMPLE_SELECT)
                                    ElMessage.success('绘制点位成功！')

                                    this.initData(this.mapA)
                                    this.initData(this.mapB)
                                }
                            }
                        })
                    })
                    new Compare(this.mapA, this.mapB, '#comparison-container', {});

                    setTimeout(() => {
                        this.firstLoad = false
                    }, 3000)
                },
                /**
                 * 创建地图
                 * @param container 容器ID
                 * @param style     样式
                 * @returns {{draw, map: mapboxgl.Map}}
                 */
                addMap(container, style) {
                    const map = new mapboxgl.Map({
                        accessToken: "pk.eyJ1IjoicGF1bGFuZGNvZGUiLCJhIjoiY2txdm94bmtmMGdsaDJvcGFia2N4M2ZydiJ9.wc0YPacoNAtaTrNCoZd8Fg",
                        container: container,
                        style: style,
                        center: this.mapCenter,
                        minZoom: this.minZoom,
                        maxZoom: this.maxZoom,
                        zoom: 12
                    })
                    map.doubleClickZoom.disable();
                    // 指南针控件
                    map.addControl(new mapboxGlControls.CompassControl(), 'bottom-right')
                    // 语言控件
                    map.addControl(new mapboxGlControls.LanguageControl({language: 'zh'}))
                    // 绘图控件
                    const draw = new MapboxDraw({
                        displayControlsDefault: false,
                        styles: drawStyle,
                        modes: Object.assign(MapboxDraw.modes, {
                            simple_select: SimpleSelect,
                            direct_select: DirectSelect,
                            draw_center: DrawCenter
                        })
                    })
                    map.addControl(draw)
                    map.on('load', () => {
                        this.initLayer(map)
                    })
                    return {
                        map,
                        draw
                    }
                },
                // 标记中心坐标
                setCenter() {
                    this.drawA.changeMode("draw_center")
                    this.drawB.changeMode("draw_center")
                },
                // 初始化图层
                initLayer(map) {
                    const colors = map.getStyle().name === "Mapbox Streets" ? {
                        self: '#a87d37',
                        brothers: 'rgb(15,50,227)',
                        parent: '#000'
                    } : {
                        self: 'hsl(303,83%,51%)',
                        brothers: 'rgb(83,238,224)',
                        parent: '#fff'
                    }

                    this.addEmptySource(map, selfId)
                    this.addEmptySource(map, brothersId)
                    this.addEmptySource(map, parentId)

                    this.addTextLayer(map, selfId, selfId, colors.self)

                    this.addTextLayer(map, brothersId, brothersId, colors.brothers)

                    this.addLineLayer(map, parentId, parentId, colors.parent)

                    this.initData(map)
                },
                // 初始化数据
                initData(map) {
                    if (this.noParent) {
                        return false
                    }
                    $.get(alluse.bigcenter + '/gis/' + this.dataType + '/list-all/' + this.dataId, res => {
                        if (res.code === 200) {
                            const data = res.data
                            const parent = turf.multiPolygon(data.parent.geometry.coordinates);
                            if (data.self) {
                                map.getSource(selfId).setData(data.self)
                                this.hasData = true
                            } else {
                                this.hasData = false
                            }
                            if(this.firstLoad) {
                                const bbox = turf.bbox(parent)
                                map.fitBounds(bbox, {
                                    animate: false,
                                    padding: {top: 70, bottom: 50, left: 50, right: 50}
                                })
                            }
                            this.parent = parent
                            map.getSource(parentId).setData(data.parent)
                            map.getSource(brothersId).setData(data.brothers)
                        } else {
                            this.noParent = true
                        }
                    })
                },
                /**
                 * 增加空的数据源
                 * @param map 地图
                 * @param sourceId 数据源ID
                 */
                addEmptySource(map, sourceId) {
                    if (!map.getSource(sourceId)) {
                        map.addSource(sourceId, {
                            "type": "geojson",
                            "data": {
                                type: "FeatureCollection",
                                features: []
                            }
                        })
                    }
                },
                /**
                 * 增加文本图层
                 * @param map 地图
                 * @param layerId   图层ID
                 * @param sourceId  数据源ID
                 * @param textColor 文本颜色
                 */
                addTextLayer(map, layerId, sourceId, textColor) {
                    map.loadImage('lib/mapbox/img/bus-points-equipment.png', (error, image) => {
                        if (error) throw error;
                        const img = 'bus-points-equipment-img';
                        map.addImage(img, image);

                        map.addLayer({
                            id: layerId + "-symbol",
                            type: 'symbol',
                            minzoom: 6,
                            source: sourceId,
                            layout: {
                                'icon-image': img,
                                "icon-size": ["interpolate", ["linear"],
                                    ["zoom"], 12, 0.4, 18, 1.2
                                ],
                                'text-size': ["interpolate", ["linear"],
                                    ["zoom"], 12, 12, 18, 20
                                ],
                                'text-field': ['get', 'name'],
                                'text-justify': 'center',
                                'text-offset': ["interpolate", ["linear"],
                                    ["zoom"], 12, ['literal', [0, 0.9]], 18, ['literal', [0, 1.2]]
                                ],
                                'text-anchor': 'top',
                                'text-letter-spacing': 0.2,
                                'text-max-width': 12
                            },
                            paint: {
                                'text-color': textColor
                            }
                        })
                    })
                },
                /**
                 * 增加线图层
                 * @param map 地图
                 * @param layerId     图层ID
                 * @param sourceId    数据源ID
                 * @param lineColor   线颜色
                 */
                addLineLayer(map, layerId, sourceId, lineColor) {
                    map.addLayer({
                        'id': layerId + "-line",
                        'type': 'line',
                        'source': sourceId,
                        'minzoom': 6,
                        'paint': {
                            'line-color': lineColor,
                            'line-width': 4
                        }
                    })
                }
            }
        }
    }

    module.exports = {
        onload
    };
});
